<template>
  <div class="avatar-wrap">
    <img
      :class="['avatar', isCircle ? 'avatar--round' : 'avatar--square',isBig ? 'big' : '']"
      v-if="avatarUrl"
      :src="avatarUrl"
      alt="avatar"
      class="avatar"
    />
    <div v-else>
      <div
        :class="[
          'avatar',
          'rong-avatar-theme-' + getThemeIndex(name),
          'avatar__name',
          isCircle ? 'avatar--round' : 'avatar--square',
          isBig ? 'big' : ''
        ]"
        :style="{ '--width': '0.5rem', '--height': '0.5rem', '--font-size': '12px' }"
      >
        <span :style="{ transform: onlySingleName ? '' : 'scale(.8)' }">{{
          name?.trim().substring(0, onlySingleName ? 1 : 2)
        }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, defineProps } from 'vue'
// 定义 Props
interface AvatarProps {
  avatarUrl?: string
  name: string
  isCircle?: boolean
  isBig?: boolean
  isSingleName: boolean
  userId?: string // 假设还需要 userId 用于计算主题颜色
}

const props = defineProps<AvatarProps>()

const getThemeIndex = (id) => {
  // 根据id返回固定数字，用于显示头像背景色，共11种颜色
  const LENGTH = 11
  return id ? id.slice(-1).charCodeAt(0) % LENGTH : 0
}

const onlySingleName = computed(() => props?.name?.trim().length <= 1 || props?.isSingleName)
</script>

<style scoped lang="scss">
.avatar {
  display: inline-flex;
  width: 32px;
  min-width: 32px;
  height: 32px;
}

.avatar--round {
  border-radius: 50%;
}

.avatar--square {
  border-radius: 8px;
}

.avatar__name {
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  line-height: 100% !important;
  background-color: #f7ad80;
}

.big {
  width: 36px !important;
  min-width: 36px;
  height: 36px !important;
  font-size: 18px !important;
}

.rong-avatar-theme-0 {
  background-color: #ab6bff;
}

.rong-avatar-theme-1 {
  background-color: #7576ff;
}

.rong-avatar-theme-2 {
  background-color: #3e8dff;
}

.rong-avatar-theme-3 {
  background-color: #4cbafd;
}

.rong-avatar-theme-4 {
  background-color: #5ed9c6;
}

.rong-avatar-theme-5 {
  background-color: #3fd477;
}

.rong-avatar-theme-6 {
  background-color: #fac032;
}

.rong-avatar-theme-7 {
  background-color: #ff9946;
}

.rong-avatar-theme-8 {
  background-color: #ff5757;
}

.rong-avatar-theme-9 {
  background-color: #ff7773;
}

.rong-avatar-theme-10 {
  background-color: #ff7a8d;
}
</style>
